import React, { Component } from 'react';
import PubSub from 'pubsub-js';
import { List, Toast, ActivityIndicator } from 'antd-mobile';
import {
    getMembers,
    getUserInfo,
    getAppVersion,
    getDeviceNewVersion,
    getDeviceSn,
    getUuid,
    shareQRCode,
    getWechatId,
} from '../utils';
import {audio_operate} from '../components/AudioPlayOperate'

import { yearAndMonth } from '../components/BrithdayPicker';
import VolumAdjust from '../components/VolumAdjust';

// images
import IconMembers from '../images/members.png';
import IconSoftUpdate from '../images/soft_update.png';
import IconUpgrade from '../images/upgrade_green.png';
import IconNewVersion from '../images/new_version.png';
import IconDeviceSn from '../images/device_sn.png';
import IconShareDevice from '../images/share_device.png';

const Item = List.Item;

// 设置界面
class Settings extends Component {

    constructor(props, context) {
        super(props, context);
        this.handleEdit = this.handleEdit.bind(this);
        this.handleEntryMembers = this.handleEntryMembers.bind(this);
        this.handleShareDevice = this.handleShareDevice.bind(this);
        this.handleOtaUpgrade = this.handleOtaUpgrade.bind(this);

        const members = JSON.parse(sessionStorage.getItem('members')) || [];
        const ticket = localStorage.getItem('ticket') || '';
        this.avatar = localStorage.getItem('avatar') || '';

        this.state = {
            members: members,
            deviceCurVersion: localStorage.getItem('ota_version')|| '',
            hasNewVersion: false,
            isLoading: false,
            ticket: ticket,
            user: {
                nick_name: '设置一个昵称吧',
                avatar: null,
                brithday: null,
                gender: null
            }
        }
    }

    componentDidMount() {
        this._isMounted = true;
        document.title = localStorage.getItem('device_name');
        PubSub.publish('contrlDevice', { type: audio_operate.upgrade_online, value: true });
        // 用户信息
        getUserInfo((result) => {
            if (result.errcode === 0 && result.data) {
                this.setState({
                    user: result.data
                });
            }
        });

        // 最新版本
        this.getNewVersion(() => { });

        // 家庭成员
        getMembers((result) => {
            if (result.errcode === 0) {
                sessionStorage.setItem("members", JSON.stringify(result.data));
                this.setState({
                    members: result.data
                });
            }
        });
        // 分享设备
        shareQRCode(this.state.device_sn, (result) => {
            if (result.errcode === 0) {
                const ticket = result.data.ticket || '';
                this.setState({
                    ticket: ticket
                });
                localStorage.setItem('ticket', ticket);
            }
        });

        this.checkVersion = setInterval(() => {
            const version = localStorage.getItem('ota_version') || '';
            this.setState({
                deviceCurVersion:version
            });
        },2000);
    }

    getNewVersion(callback) {
        getDeviceNewVersion(getUuid(), (result) => {
            if (this._isMounted) {
                if (result.errcode === 0) {
                    this.setState({
                        hasNewVersion: !!result.data
                    });
                    callback(0);
                } else {
                    callback(-1);
                }
            }
        })
    }


    componentWillUnmount() {
        this._isMounted = false;
        if (this.dialog) {
            this.dialog.close();
        }
        Toast.hide();
        clearInterval(this.checkVersion);
    }

    handleEdit() {
        this.props.history.push({
            pathname: '/editinfo',
            user: this.state.user,
            device_id: this.state.device_id,
        })
    }

    handleEntryMembers() {
        this.props.history.push({
            pathname: '/members',
            members: this.state.members,
        })
    }
    // 分享设备
    handleShareDevice() {
        const ticket = localStorage.getItem('ticket') || '';
        if (ticket) {
            this.turnToShareDevice(ticket);
        } else {
            shareQRCode(getDeviceSn(), (result) => {
                if (result.errcode === 0) {
                    const ticket = result.data.ticket || '';
                    this.setState({
                        ticket: ticket
                    });
                    localStorage.setItem('ticket', ticket);
                    this.turnToShareDevice(ticket);
                } else {
                    Toast.show('分享设备失败', 1, false);
                }
            });
        }
    }

    // 跳转到分享设备界面
    turnToShareDevice(ticket) {
        window.location.href = window.location.protocol + '//' + window.location.host + '/?func=share_device&wechat_id=' + getWechatId() + '&ticket=' + ticket;
    }

    handleOtaUpgrade() {
        this.getNewVersion((ret) => {
            if (ret === -1) {
                Toast.show('获取设备最新版本失败', 1, false)
            } else {
                if (this.state.hasNewVersion) {
                    this.props.history.push({
                        pathname: '/upgrade/:' + this.state.deviceCurVersion + '/:' + getUuid()
                    })
                } else {
                    Toast.show('已经是最新版本', 1, false);
                }
            }
        })
    }

    // 序列号后缀
    getSunffix() {
        const arr = getDeviceSn().split('_');
        return arr[arr.length - 1];
    }

    getBackground(height) {
        return (<div style={{ height: height, background: '#eeeeee', width: '100%' }} />);
    }
    render() {
        return (
            <div>
                <div style={{ background: '#ffffff', width: '100%' }}>
                    {this.getBackground(16)}
                    <Item
                        arrow="horizontal"
                        onClick={this.handleEdit}>
                        <div style={styles.div_header}>
                            <div style={styles.div_header_img}>
                                <img src={this.avatar} style={{
                                    width: '42px',
                                    height: '42px',
                                    borderRadius: '5px',
                                }} alt='' />
                            </div>
                            <div style={{ marginLeft: "10px", height: "56px", padding: "5px" }}>
                                <p style={styles.name}>{this.state.user.nick_name}</p>
                                <span style={{
                                    width: "80px",
                                    color: "#888",
                                    fontSize: "12px",
                                    display: "flex",
                                }}>{yearAndMonth(this.state.user.brithday)}</span>
                            </div>
                        </div>
                    </Item>
                    {this.getBackground(1)}

                    <Item
                        arrow="horizontal"
                        extra={<p style={{ fontSize: '13px' }}>{this.state.members.length + "个"}</p>}
                        onClick={this.handleEntryMembers}>
                        <div style={styles.item_div}>
                            <div style={styles.item_image}>
                                <img src={IconMembers} alt='' style={styles.icon} />
                            </div>
                            <div style={styles.item_text}>
                                <p style={styles.text}>家庭成员</p>
                            </div>
                        </div>
                    </Item>

                    {this.getBackground(8)}
                    <Item
                        arrow="horizontal"
                        onClick={this.handleShareDevice}>
                        <div style={styles.item_div}>
                            <div style={styles.item_image}>
                                <img src={IconShareDevice} alt='' style={styles.icon} />
                            </div>
                            <div style={styles.item_text}>
                                <p style={styles.text}>分享设备</p>
                            </div>
                        </div>
                    </Item>

                    {this.getBackground(8)}

                    <Item
                        onClick={this.handleOtaUpgrade}
                        extra={<p style={{ fontSize: '13px', marginRight: "18px" }}>{this.state.deviceCurVersion}</p>}>
                        <div style={styles.item_div}>
                            <div style={styles.item_image}>
                                <img src={IconUpgrade} alt='' style={styles.icon} />
                            </div>
                            <div style={styles.item_text}>
                                <p style={styles.text}>固件版本</p>
                            </div>
                            {
                                this.state.hasNewVersion &&
                                <div style={{
                                    height: "42px",
                                    display: 'flex',
                                    justifyContent: 'end',
                                    alignItems: 'center',
                                    paddingLeft: "24px",
                                }}>
                                    <img src={IconNewVersion} style={{ height: "16px", width: "48px" }} alt="" />
                                </div>
                            }
                        </div>
                    </Item>

                    {this.getBackground(1)}
                    <Item
                        onClick={() => { console.log('') }}
                        extra={<p style={{ fontSize: '11px' }}>{this.getSunffix()}</p>}>
                        <div style={styles.item_div}>
                            <div style={styles.item_image}>
                                <img src={IconDeviceSn} alt='' style={styles.icon} />
                            </div>
                            <div style={styles.item_text}>
                                <p style={styles.text}>设备序列号</p>
                            </div>
                        </div>
                    </Item>

                    {this.getBackground(1)}
                    <Item
                        onClick={() => { console.log('') }}
                        extra={<p style={{ fontSize: '13px', marginRight: 18 }}>{getAppVersion()}</p>}>
                        <div style={styles.item_div}>
                            <div style={styles.item_image}>
                                <img src={IconSoftUpdate} alt='' style={styles.icon} />
                            </div>
                            <div style={styles.item_text}>
                                <p style={styles.text}>程序版本</p>
                            </div>
                        </div>
                    </Item>

                </div >
                {
                    this.state.showVolume &&
                    <VolumAdjust
                        volume={this.state.volume}
                        volumAction={this.volumAction.bind(this)} />
                }

                <ActivityIndicator
                    toast
                    text="正在获取设备版本..."
                    animating={this.state.isLoading}
                />

            </div>
        );
    }
}

export default Settings;

const styles = {
    icon: {
        width: '30px',
        height: '30px',
    },

    brithday: {
        width: "95%",
        color: "#ddd",
        fontSize: '12px',
        marginTop: 5
    },

    member: {
        width: '100%',
        height: '100%',
        position: 'fixed',
        background: '#ffffff',
        zIndex: 4,
        top: 0,
    },
    div_header: { width: '100%', height: "56px", display: 'flex' },
    div_header_img: { height: '56px', alignItems: "center", justifyContent: 'center', display: 'flex' },
    item_div: { width: '100%', height: "42px", display: 'flex' },
    item_image: { height: '42px', alignItems: "center", justifyContent: 'center', display: 'flex' },
    item_text: {
        paddingLeft: 18,
        height: '42px',
        display: 'flex',
        justifyContent: 'center',
        alignItems: 'center',
    },

    text: {
        color: "#000",
        fontSize: '16px',
    },
    name: {
        width: document.documentElement.clientWidth / 5 * 3,
        marginRight: 16,
        paddingBottom: 0,
        marginBottom: 3,
        color: "#15a67c",
        fontSize: "15px",
        marginTop: 5,
        overflow: "hidden",
        textOverflow: "ellipsis",
        whiteSpace: "nowrap",
    }
};

